/*
 * Copyright 2013 Robert Peszek.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fpig.lists.functions

import fpig.lists.structures.FunList
import fpig.lists.structures.LazyList
import fpig.util.CallUtil

/**
* Functions for moving in and out between Groovy Lists and FunList (Lazy List)
*
* http://code.google.com/p/fpiglet/
* @author Robert Peszek
*/

class InAndOutOfF {
    static Closure funlistIn = {List fromL, Map props=null->
        FunList result = LazyList.EMPTYLIST;
        fromL.reverseEach{ result = result.prepend(it) } //TODO should prepend be used or build?
        result
    }

    static Closure funlistOutTakeC = { long n, FunList flist ->
        def result = []; int i=0; boolean fetchAll = n<0; def current = flist
        while(fetchAll || i<n) {
            //very ugly imperative code, sorry!
            i +=1;
            if(!current.empty) {
                result.add(current.head);
                current = current.tail
            }
            else {
                break
            }
        }
        result
    }
    static Closure funlistOutTake = CallUtil.toFunction funlistOutTakeC
    static Closure funlistOut = funlistOutTake(-1)
	
	static Closure withFunList = CallUtil.toFunction {Closure f, groovyList ->
		def output = f << InAndOutOfF.funlistIn << groovyList
		if(output instanceof FunList)
		   InAndOutOfF.funlistOut output
		else 
		   output
	}
	
	static Closure withFunListTake = CallUtil.toFunction {n, Closure f, groovyList ->
		InAndOutOfF.funlistOutTake(n) << f << InAndOutOfF.funlistIn << groovyList	
	}
}
